/* eslint-disable no-undef */
importScripts('./workbox-sw.js')
if (workbox) {
  console.log('Yay! Workbox is loaded 🎉')
} else {
  console.log("Boo! Workbox didn't load 😬")
}

workbox.core.setCacheNameDetails({
  prefix: 'AI-F10',
  suffix: 'v1.0.4'
})
workbox.core.skipWaiting() // 强制等待中的 Service Worker 被激活
workbox.core.clientsClaim() // Service Worker 被激活后使其立即获得页面控制权
workbox.precaching.precacheAndRoute(self.__precacheManifest || []) // 设置预加载

// 插件：在请求失败时从缓存中删除该条目
class RemoveFailedRequestPlugin {
  async cacheWillUpdate({ response }) {
    if (!response || response.status !== 200) {
      return null
    }
    return response
  }

  async fetchDidFail({ request, cacheName }) {
    const cache = await caches.open(cacheName)
    await cache.delete(request)
  }
}

// 缓存html主文件
workbox.routing.registerRoute(
  /.*\.html/,
  // 优先使用网络，网络获取失败后使用缓存
  new workbox.strategies.NetworkFirst({
    cacheName: 'html-cache',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 5, // 最大缓存数
        maxAgeSeconds: 1 * 24 * 60 * 60 // 缓存时间：1天
      }),
      new workbox.cacheableResponse.Plugin({
        statuses: [200] // 只缓存状态码为200的响应
      }),
      new RemoveFailedRequestPlugin()
    ]
  })
)

// 缓存CDN资源，只使用缓存，不更新
workbox.routing.registerRoute(
  /^https:\/\/s\.thsi\.cn\/.*/,
  // 优先使用缓存，只有在缓存没有时才使用网络请求
  new workbox.strategies.CacheFirst({
    cacheName: 'cdn-assets',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 60,
        maxAgeSeconds: 30 * 24 * 60 * 60 // 设置缓存有效期为30天
      }),
      new workbox.cacheableResponse.Plugin({
        statuses: [200] // 只缓存状态码为200的响应
      }),
      new RemoveFailedRequestPlugin()
    ]
  })
)

// 缓存特定API请求
workbox.routing.registerRoute(
  // 匹配特定前缀的URL
  new RegExp('/basicapi'),
  // 优先请求网络，网络失败后使用缓存
  new workbox.strategies.NetworkFirst({
    cacheName: 'api-cache',
    plugins: [
      // 设置缓存时间
      new workbox.expiration.Plugin({
        maxEntries: 50, // 最大缓存数
        maxAgeSeconds: 1 * 60 // 缓存时间：1分钟
      }),
      new workbox.cacheableResponse.Plugin({
        statuses: [200] // 只缓存状态码为200的响应
      }),
      new RemoveFailedRequestPlugin()
    ]
  })
)

// 清理已缓存的失败资源
self.addEventListener('activate', (event) => {
  event.waitUntil(
    (async () => {
      const cacheNames = await caches.keys()
      for (const cacheName of cacheNames) {
        const cache = await caches.open(cacheName)
        const requests = await cache.keys()
        for (const request of requests) {
          const response = await cache.match(request)
          if (!response || response.status !== 200) {
            await cache.delete(request)
          }
        }
      }
      self.clients.claim()
    })()
  )
})
